import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_axrjc/datasource/network/bean/Account.dart';
import 'package:flutter_axrjc/datasource/network/bean/UserBean.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Util {
  static var random = Random();

  static void setUi() {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.dark));
  }

  static Future saveUser(UserBean? userBean) async {
    SharedPreferences share = await SharedPreferences.getInstance();
    await share.setString(
        "user", userBean != null ? jsonEncode(userBean.toJson()) : '');
  }

  static bool isPassword(String password) {
    RegExp regex = RegExp(r'^(?=.*[a-zA-Z])(?=.*[0-9]).{6,12}$');
    return regex.hasMatch(password);
  }

  static DateTime? string2Date(String dateStr,
      {String pattern = "yyyy-MM-dd HH:mm:ss"}) {
    final formatter = DateFormat(pattern);
    try {
      return formatter.parse(dateStr);
    } catch (e) {
      print(e);
      return null;
    }
  }

  static String? date2String(
    DateTime date, {
    // String pattern = "yyyy-MM-dd HH:mm:ss",
    String pattern = "yyyy-MM-dd",
  }) {
    final formatter = DateFormat(pattern);
    try {
      return formatter.format(date);
    } catch (e) {
      return null;
    }
  }

  static List<List<Color>> gradient = [
    [const Color(0xffF7D25D), const Color(0xffE3801D)],
    [const Color(0xff918CF1), const Color(0xffA863F5)],
    [const Color(0xffF56C6C), const Color(0xffEF9785)]
  ];
  static List<List<Color>> shuffleGradient() {
    List<List<Color>> shuffledGradient = List.from(gradient); // 复制原始列表
    shuffledGradient.shuffle(Random()); // 使用shuffle方法随机打乱顺序
    return shuffledGradient; // 返回打乱顺序后的列表
  }

  static Future saveAccount(Account account) async {
    SharedPreferences share = await SharedPreferences.getInstance();
    await share.setString("phone", account.phone);
    await share.setString("password", account.password);
    await share.setBool("lastSaveAccount", account.lastSaveAccount);
  }

  static Future<Account> getAccount() async {
    SharedPreferences share = await SharedPreferences.getInstance();
    await share.setBool("lastSaveAccount", true);
    return Account(
        phone: share.getString("phone") ?? '',
        password: share.getString("password") ?? '',
        lastSaveAccount: share.getBool("lastSaveAccount") ?? false);
  }
}
